/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Interfaces.ApparentModalI;
import Model.Playlist;
import Model.Playlistsong;
import Model.Song;
import java.awt.Frame;
import java.awt.Image;
import javax.imageio.ImageIO;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import src.General;


/**
 *
 *
 */
public class MngPlaylistAddSong extends javax.swing.JFrame implements ApparentModalI{

    private MngPlaylist prFrmMngPlaylist;
    private EntityManager prEM;
    private Model.Playlist prSelectedPlaylist;
    private String prUsername;
    private final JFrame next = null;
    
    /**
     * Creates new form MngPlaylistAddSong
     */
    public MngPlaylistAddSong(MngPlaylist frmMngPlaylist, Playlist selectedPlaylist, EntityManager em, String username) 
    {
        try 
        {
            this.prFrmMngPlaylist = frmMngPlaylist;
            this.prEM = em;
            this.prUsername = username;
            
            this.prSelectedPlaylist = selectedPlaylist;
            
            initComponents();

            Image applicationImage = ImageIO.read(getClass().getResource("/Images/note1.png"));
            this.setIconImage(applicationImage);

        } 
        catch (Exception ex) 
        {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        songsQuery = java.beans.Beans.isDesignTime() ? null : prEM.createQuery("SELECT s FROM Song s ORDER BY s.songTitle");
        songsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(songsQuery.getResultList());
        jScrollPane1 = new javax.swing.JScrollPane();
        songsTable = new javax.swing.JTable();
        btnExit = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        btnAdd = new javax.swing.JButton();
        lblSongs = new javax.swing.JLabel();
        lblSearch = new javax.swing.JLabel();
        txtSearchField = new javax.swing.JTextField();
        btnSearch = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Radio Station - Φόρμα Διαχείρισης Λίστας - Εισαγωγή Τραγουδιού");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        songsTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, songsList, songsTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${songTitle}"));
        columnBinding.setColumnName("Τίτλος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumId.artistId}"));
        columnBinding.setColumnName("Καλλιτέχνης");
        columnBinding.setColumnClass(Model.Artist.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumId.musicGroupId.musicGroupName}"));
        columnBinding.setColumnName("Συγκρότημα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${duration}"));
        columnBinding.setColumnName("Διάρκεια (sec)");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(songsTable);

        btnExit.setText("Έξοδος");
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });

        btnAdd.setText("Εισαγωγή Τραγουδιού");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        lblSongs.setText("Διαθέσιμα Τραγούδια");

        lblSearch.setText("Κριτήριο Αναζήτησης");

        btnSearch.setText("Αναζήτηση");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtSearchField)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSearch))
                    .addComponent(lblSongs)
                    .addComponent(lblSearch))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnExit)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnAdd)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblSearch)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtSearchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSearch))
                .addGap(18, 18, 18)
                .addComponent(lblSongs)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(btnAdd)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnExit)
                .addGap(4, 4, 4))
        );

        bindingGroup.bind();

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
       // this.prFrmMngPlaylist.setEnabled(true);
    }//GEN-LAST:event_formWindowClosing

    private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
        try 
        {
            //this.prFrmMngPlaylist.setEnabled(true);
            General.closeWindowX(this);
        } 
        catch (Exception ex) 
        {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnExitActionPerformed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        try
        {
            Song selectedSong;
            Playlistsong prPlaylistSong;
            int orderNum = 1;
            boolean blnPreviouslyDeleted = false;
            
            int selectedSongRow = this.songsTable.getSelectedRow();
            
            if(selectedSongRow == -1)
            {
                JOptionPane.showMessageDialog(this, "Παρακαλώ επιλέξτε πρώτα το τραγούδι που επιθυμείτε να προσθέσετε!", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
            }
            else
            {
                selectedSong = songsList.get(songsTable.convertRowIndexToModel(selectedSongRow));                
                
                for (Playlistsong objPlaylistsong : this.prFrmMngPlaylist.pbPlaylistSongsToBeDeletedList) 
                {
                    if (objPlaylistsong.getSongId() == selectedSong)
                    {
                        blnPreviouslyDeleted = true;
                        this.prFrmMngPlaylist.pbPlaylistSongsToBeDeletedList.remove(objPlaylistsong);
                        this.prFrmMngPlaylist.playlistSongsList.add(objPlaylistsong);
                        break;
                    }
                }
                
                if (blnPreviouslyDeleted == false)
                {
                    prPlaylistSong = new Playlistsong();
                    prPlaylistSong.setPlaylistId(prSelectedPlaylist);
                    prPlaylistSong.setSongId(selectedSong);
                    prPlaylistSong.setCreatedBy(prUsername);

                    for (Playlistsong objPlaylistsong : prFrmMngPlaylist.playlistSongsList) 
                    {
                        if (objPlaylistsong.getSongId() == selectedSong)
                        {
                            throw new Exception("Το τραγούδι '" + selectedSong.getSongTitle() + "' έχει προστεθεί ήδη στην συγκεκριμένη λίστα!");
                        }
                        if (objPlaylistsong.getOrderNum() >= orderNum)
                        {
                            orderNum = objPlaylistsong.getOrderNum() + 1;
                        }
                    }                
                    prPlaylistSong.setOrderNum(orderNum);

                    this.prFrmMngPlaylist.pbPlaylistSongsToBeAddedList.add(prPlaylistSong);
                    
                    this.prFrmMngPlaylist.playlistSongsList.add(prPlaylistSong);
                                   
                }
                
                JOptionPane.showMessageDialog(this, "Η προσθήκη ολοκληρώθηκε επιτυχώς!", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                
                this.prFrmMngPlaylist.HandleButtons();
            }
        }
        catch (Exception ex)
        {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        try
        {
            this.txtSearchField.setText(this.txtSearchField.getText().trim());
            
            if (txtSearchField.getText().isEmpty())
            {
                songsQuery = prEM.createQuery("SELECT s FROM Song s ORDER BY s.songTitle");
                this.songsList.clear();
                this.songsList.addAll(songsQuery.getResultList());
            }
            else
            {
                songsQuery = prEM.createQuery("SELECT s FROM Song s WHERE s.songTitle like :searchValue UNION SELECT s FROM Song s WHERE s.albumId.musicGroupId.musicGroupName like :searchValue UNION SELECT s FROM Song s WHERE s.albumId.artistId.artisticName like :searchValue or s.albumId.artistId.firstname like :searchValue or s.albumId.artistId.lastname like :searchValue").setParameter("searchValue", "%"+txtSearchField.getText()+"%");

                this.songsList.clear();
                this.songsList.addAll(songsQuery.getResultList());
            }
        }
        catch (Exception ex)
        {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnSearchActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnSearch;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblSearch;
    private javax.swing.JLabel lblSongs;
    private java.util.List<Model.Song> songsList;
    private javax.persistence.Query songsQuery;
    private javax.swing.JTable songsTable;
    private javax.swing.JTextField txtSearchField;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    @Override
    public Frame getCaller() {
        return this.prFrmMngPlaylist;
    }

    @Override
    public Frame getNext() {
        return this.next;
    }

    @Override
    public void setCallersNextNull() {
        ((ApparentModalI) this.prFrmMngPlaylist).setNext(null);
    }

    @Override
    public void setNext(Frame w) {
       throw new UnsupportedOperationException("modal:error"); //To change body of generated methods, choose Tools | Templates.
    }

}
